package com.SMP.utils;

import com.SMP.model.httpModel.AddFace;
import com.SMP.model.httpModel.FaceMsg;
import com.SMP.model.httpModel.ScannerFace;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import okhttp3.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.util.*;

/**
 * @program: SchoolManagementPlatform
 * @description:
 * @author: WYHY
 * @create: 2018-12-26 17:18
 **/
public class Face {

//    private static String token;

//    public static String loginFace() {
//        Future<HttpResponse<JsonNode>> response = Unirest.post("http://183.3.223.120:18762/ifaas-authority/oauth/token")
//                .header("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
//                .header("token", "Basic c3VwZXJ1c2VyOjEyMzQ1Ng==")
//                .body("username=superuser&password=e10adc3949ba59abbe56e057f20f883e&grant_type=password&scope=read%20write&undefined=")
//                .asJsonAsync(new Callback<JsonNode>() {
//                    @Override
//                    public void completed(HttpResponse<JsonNode> httpResponse) {
//                        int code = httpResponse.getStatus();
//                        JsonNode body = httpResponse.getBody();
//                        JSONObject object = body.getObject();
//                        System.out.println(LocalDateTime.now()+"\tgettoken>>>"+"Bearer " + object.get("access_token"));
//                        token="Bearer " + object.get("access_token");
//                    }
//
//                    @Override
//                    public void failed(UnirestException e) {
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void cancelled() {
//                        System.out.println("The request has been cancelled");
//                    }
//                });
//        return token;//通过out.Stream.toByteArray获取到写的数据;
//    }

//    public static String sendImgType(MultipartFile file) {
//        String id="";
//        try {
//            //要上传的文件地址
//            String filepath = "D:\\photo\\people\\"+file.getOriginalFilename();
//
//            String urlStr = "http://localhost:8080/wxchar_menu/upload";
//
//            Map<String, String> textMap = new HashMap<String, String>();
//
//            textMap.put("type", "0");
//
//            Map<String, String> fileMap = new HashMap<String, String>();
//
//            //随便写入的参数
//            fileMap.put("file", filepath);
//            String jsonString=formUpload("http://183.3.223.120:18762/ifaas-collection/collection/api/upload/image/1.0", textMap, fileMap);
//            JSONObject result = new JSONObject(jsonString);
//            if (result.getLong("respCode") == 10000000l) {
//                JSONObject object = result.getJSONObject("data");
//                id = object.getString("id");
//            } else {
//                id = "error";
//                System.out.println("异常信息》》》》"+result.getString("respMessage"));
//            }
//            File file1=new File(filepath);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return id;
////        return null;
//    }
//
//    public static String formUpload(String urlStr, Map<String, String> textMap, Map<String, String> fileMap) {
//        String res = "";
//        HttpURLConnection conn = null;
//        String BOUNDARY = "----WebKitFormBoundary7MA4YWxkTrZu0gW"; // boundary就是request头和上传文件内容的分隔符
//        try {
//            URL url = new URL(urlStr);
//            conn = (HttpURLConnection) url.openConnection();
//            conn.setConnectTimeout(5000);
//            conn.setReadTimeout(30000);
//            conn.setDoOutput(true);
//            conn.setDoInput(true);
//            conn.setUseCaches(false);-
//            conn.setRequestMethod("POST");
////            conn.setRequestProperty("Connection", "Keep-Alive");
////            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
//            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
//            conn.setRequestProperty("token", token);
//
//            OutputStream out = new DataOutputStream(conn.getOutputStream());
//            // text
//            if (textMap != null) {
//                StringBuffer strBuf = new StringBuffer();
//                Iterator iter = textMap.entrySet().iterator();
//                while (iter.hasNext()) {
//                    Map.Entry entry = (Map.Entry) iter.next();
//                    String inputName = (String) entry.getKey();
//                    String inputValue = (String) entry.getValue();
//                    if (inputValue == null) {
//                        continue;
//                    }
//                    strBuf.append("\r\n").append("--").append(BOUNDARY)
//                            .append("\r\n");
//                    strBuf.append("Content-Disposition: form-data; name=\""
//                            + inputName + "\"\r\n\r\n");
//                    strBuf.append(inputValue);
//                }
//                out.write(strBuf.toString().getBytes());
//            }
//
//            // file
//            if (fileMap != null) {
//                Iterator iter = fileMap.entrySet().iterator();
//                while (iter.hasNext()) {
//                    Map.Entry entry = (Map.Entry) iter.next();
//                    String inputName = (String) entry.getKey();
//                    String inputValue = (String) entry.getValue();
//                    if (inputValue == null) {
//                        continue;
//                    }
//                    File file = new File(inputValue);
//                    String filename = file.getName();
//                    String contentType = new MimetypesFileTypeMap()
//                            .getContentType(file);
//                    if (filename.endsWith(".png")) {
//                        contentType = "image/png";
//                    }
//                    if (contentType == null || contentType.equals("")) {
//                        contentType = "application/octet-stream";
//                    }
//
//                    StringBuffer strBuf = new StringBuffer();
//                    strBuf.append("\r\n").append("--").append(BOUNDARY)
//                            .append("\r\n");
//                    strBuf.append("Content-Disposition: form-data; name=\""
//                            + inputName + "\"; filename=\"" + filename
//                            + "\"\r\n");
//                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");
//
//                    out.write(strBuf.toString().getBytes());
//
//                    DataInputStream in = new DataInputStream(
//                            new FileInputStream(file));
//                    int bytes = 0;
//                    byte[] bufferOut = new byte[1024];
//                    while ((bytes = in.read(bufferOut)) != -1) {
//                        out.write(bufferOut, 0, bytes);
//                    }
//                    in.close();
//                }
//            }
//
//            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
//            out.write(endData);
//            out.flush();
//            out.close();
//
//            // 数据返回
//            StringBuffer strBuf = new StringBuffer();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(
//                    conn.getInputStream()));
//            String line = null;
//            while ((line = reader.readLine()) != null) {
//                strBuf.append(line).append("\n");
//            }
//            res = strBuf.toString();
//            reader.close();
//            reader = null;
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            if (conn != null) {
//                conn.disconnect();
//                conn = null;
//            }
//        }
//        return res;
//    }
//
//    public static boolean inpeople(People people,String id) {
//        final boolean[] isIn = {false};
//        try {
//            HttpResponse<String> response1 = Unirest.get("http://183.3.223.120:18762/ifaas-collection/collection/api/image/search/face/1.0?id="+id)
//                    .header("Content-Type", "charset=UTF-8")
//                    .header("token", token)
//                    .asString();
//            JSONObject object=new JSONObject(response1.getBody());
//            if (object.getLong("respCode")==10000000l){
//                Map map=new HashMap();
//                map.put("faceId",people.getStandby6());
//                map.put("cidValue",people.getStandby2());
//                map.put("name",people.getName());
//                map.put("gender",people.getSex());
//                map.put("staticTypeId",9);
//                JSONObject jsonObject=new JSONObject(map);
//                HttpResponse<String> response = Unirest.post("http://183.3.223.120:18762/ifaas-collection/collection/api/static/infoSingle/1.0")
//                        .header("Content-Type", "application/json")
//                        .header("token", token)
//                        .body(jsonObject.toString())
//                        .asString();
//                JSONObject object1=new JSONObject(response.getBody());
//                if (object1.getLong("respCode")==10000000){
//                    System.out.println("录入人员信息接口"+object1.getLong("respCode"));
//                    isIn[0] = true;
//                }else {
//                    System.out.println(object.get("respMessage"));
//                    isIn[0] = false;
//                }
//            }else {
//                System.out.println(object.get("respMessage"));
//                isIn[0] = false;
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return isIn[0];
//    }
//
//    public static List<String> face(String img_base64) {
//        List<String> pelple=new ArrayList<String>();
//        try {
//            HttpResponse<String> response = Unirest.post("http://183.3.223.120:18762/ifaas-search/search/general/searchFaceByAttribute/1.0")
//                    .header("Content-Type", "application/json")
//                    .header("token", token)
//                    .body("{\n\t\"type\":2,\n\t\"scoreThreshold\":0.9,\n\t\"dataType\":2,\n\t\"imageData\":\""+Utils.replaceBlank(img_base64)+"\"\n}")
//                    .asString();
//            JSONObject object=new JSONObject(response.getBody());
//            if (object.getLong("respCode")==12000000){
//                JSONArray arr=object.getJSONArray("data");
//                for (int i=0;i<arr.length();i++){
//                    JSONObject obj=arr.getJSONObject(i);
//                    pelple.add(obj.getString("id"));
//                }
//            }else {
//                System.out.println(object.get("respMessage"));
//            }
//        } catch (UnirestException e) {
//            e.printStackTrace();
//        }
//
//        return pelple;
//    }

    public static void main(String[] arg0){
//        Scanner scanner=new Scanner(System.in);
//        String img64=scanner.next();
//        scannerFace(img64,"testClazz",85.5,10);
//        addFaceMsg(new File("D:/UpupooResource/config/_/桌面/电子班牌项目/tou.jpg"));
        System.out.println(createDB("testClazz4"));
    }

    public static  boolean createDB(String name){
        try {
            OkHttpClient client = new OkHttpClient();

            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, "{\n\t\"name\":\""+name+"\"\n}");
            Request request = new Request.Builder()
                    .url("http://smp-face.dev.genolo.cn/library/add")
                    .post(body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            AddFace face=JSONObject.parseObject(response.body().string(),AddFace.class);
            if (face.getStatus()==200){
                return true;
            }else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static String addFaceMsg( MultipartFile file){
        if (file != null) {
            String faceId=Utils.getUUID();
            try {
                InputStream inputStream=file.getInputStream();
                BASE64Encoder encoder = new BASE64Encoder();
                byte[] img=new byte[inputStream.available()];
                inputStream.read(img);
                inputStream.close();
                String img64=encoder.encode(img);
                OkHttpClient client = new OkHttpClient();
                MediaType mediaType = MediaType.parse("application/json");
                RequestBody body = RequestBody.create(mediaType, "{\r\n    \"name\":\"testClazz\",\r\n    \"imageBase64\":\""+img64+"\",\r\n    \"customId\":\""+faceId+"\"\r\n}");
                Request request = new Request.Builder()
                        .url("http://smp-face.dev.genolo.cn/face/add")
                        .post(body)
                        .addHeader("Content-Type", "application/json")
                        .build();
                Response response = client.newCall(request).execute();
                AddFace face=JSONObject.parseObject(response.body().string(), AddFace.class);
                if (face.getStatus()!=200){
                    faceId=null;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return faceId;
        }else {
            return null;
        }
    }

    public static String scannerFace (String img64,String dbName,double score,int topn) throws Exception {
        String faceid=null;
        OkHttpClient client = new OkHttpClient();

        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\r\n    \"names\":\""+dbName+"\",\r\n    \"imageBase64\":\""+img64+"\",\r\n    \"score\":"+score+",\r\n    \"topn\":"+topn+"\r\n}\r\n");
        Request request = new Request.Builder()
                .url("http://smp-face.dev.genolo.cn/face/compareN")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        ScannerFace<List<FaceMsg>> scannerFace=JSONObject.parseObject(response.body().string(),new TypeReference<ScannerFace<List<FaceMsg>>>(){});
        if (scannerFace.getFaceDatas()!=null){
            System.out.println(scannerFace.getFaceDatas().get(0).getCustomId());
            faceid=scannerFace.getFaceDatas().get(0).getCustomId();
        }
        return faceid;
    }

}
